package com.koo.modules.purchase.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.koo.common.constant.CodeConstant;
import com.koo.common.utils.*;
import com.koo.common.vo.AuditParams;
import com.koo.framework.feign.SystemFeignService;
import com.koo.modules.purchase.dao.PurchaseReceiveOrderDao;
import com.koo.modules.purchase.entity.PurchaseReceiveOrderDetailEntity;
import com.koo.modules.purchase.entity.PurchaseReceiveOrderEntity;
import com.koo.modules.purchase.entity.PurchasesInboundOrderDetailEntity;
import com.koo.modules.purchase.entity.PurchasesInboundOrderEntity;
import com.koo.modules.purchase.entity.vo.PurchaseQueryVo;
import com.koo.modules.purchase.service.PurchaseReceiveOrderDetailService;
import com.koo.modules.purchase.service.PurchaseReceiveOrderService;
import com.koo.modules.purchase.service.PurchasesInboundOrderDetailService;
import com.koo.modules.purchase.service.PurchasesInboundOrderService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class PurchaseReceiveOrderServiceImpl extends ServiceImpl<PurchaseReceiveOrderDao, PurchaseReceiveOrderEntity> implements PurchaseReceiveOrderService {

    @Autowired
    private PurchaseReceiveOrderDetailService purchaseReceiveOrderDetailService;
    @Autowired
    private PurchasesInboundOrderDetailService purchasesInboundOrderDetailService;
    @Autowired
    private PurchasesInboundOrderService purchasesInboundOrderService;
    @Autowired
    private SystemFeignService systemFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {

        QueryWrapper<PurchaseReceiveOrderEntity> wrapper = new QueryWrapper<>();
        List<Long> ids = new ArrayList<>();
        boolean isItemQuery = false;

        Object dataForm = params.get("dataForm");
        if (dataForm != null) {
            PurchaseQueryVo queryVo = JSON.parseObject(dataForm + "", PurchaseQueryVo.class);
            String queryDates = queryVo.getQueryDates();
            Integer auditStatus = queryVo.getAuditStatus();
            String key = queryVo.getKey();
            String queryField = queryVo.getQueryField();
            String itemKey = queryVo.getItemKey();
            String queryItemField = queryVo.getQueryItemField();

            if (queryVo != null) {
                //子查询，获取明细ID
                if (MyStrUtil.isNotEmpty(itemKey) && MyStrUtil.isNotEmpty(queryItemField)) {
                    isItemQuery = true;
                    QueryWrapper<PurchaseReceiveOrderDetailEntity> itemWrapper = new QueryWrapper<>();
                    itemWrapper.like(queryItemField, itemKey);
                    List<PurchaseReceiveOrderDetailEntity> list = purchaseReceiveOrderDetailService.list(itemWrapper);
                    if (CollectionUtils.isNotEmpty(list)) {
                        for (PurchaseReceiveOrderDetailEntity detailEntity : list) {
                            ids.add(detailEntity.getReceiveId());
                        }
                    }
                }
                if (MyStrUtil.isNotEmpty(queryDates)) {
                    String[] queryDateArr = queryDates.split(",");
                    String startDate = queryDateArr[0];
                    String endDate = queryDateArr[1];
                    wrapper.ge(MyStrUtil.isNotEmpty(startDate), "receive_date", startDate);
                    wrapper.le(MyStrUtil.isNotEmpty(endDate), "receive_date", endDate);
                }
                wrapper.eq(auditStatus != null, "IFNULL(audit_status, 0)", auditStatus);
                wrapper.like(StringUtils.isNotBlank(queryField) && StringUtils.isNotBlank(key), queryField, key);
            }
        }

        IPage<PurchaseReceiveOrderEntity> page = new Query<PurchaseReceiveOrderEntity>().getPage(params);
        if (isItemQuery) {
            if (CollectionUtils.isNotEmpty(ids)) {
                page = baseMapper.listPage(page, wrapper, ids);
            }
        } else {
            page = baseMapper.selectPage(page, wrapper);
        }
        return new PageUtils(page);
    }

    @Override
    public List<PurchaseReceiveOrderEntity> listByStoreId(Long storeId) {
        LambdaQueryWrapper<PurchaseReceiveOrderEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(MyStrUtil.isNotEmpty(storeId), PurchaseReceiveOrderEntity::getStoreId, storeId);
        return this.list(wrapper);
    }

    @Override
    @Transactional
    public void audit(AuditParams auditParams) {
        //1、修改表单审核状态
        if (auditParams != null && MyStrUtil.isNotEmpty(auditParams.getIds())) {
            String ids = auditParams.getIds();
            String[] idArr = ids.split(",");
            for (int i = 0; i < idArr.length; i++) {
                String id = idArr[i];
                PurchaseReceiveOrderEntity receiveOrderEntity = baseMapper.selectById(id);
                if (receiveOrderEntity != null) {
                    receiveOrderEntity.setAuditStatus(auditParams.getAuditStatus());
                    receiveOrderEntity.setAuditNote(auditParams.getAuditOptions());
                    baseMapper.updateById(receiveOrderEntity);
                }

                //2、插入数据到入库单
                PurchasesInboundOrderEntity inboundOrderEntity = new PurchasesInboundOrderEntity();
                BeanUtils.copyProperties(receiveOrderEntity, inboundOrderEntity);
                String inBoundNo = CodeConstant.RK + UserUtils.getStoreCode() + MyDateUtil.format(new Date(), "yyyyMMddHHmmss");
                inboundOrderEntity.setInboundNo(inBoundNo);
                inboundOrderEntity.setInboundDate(new Date());
                inboundOrderEntity.setAuditNote("");
                inboundOrderEntity.setAuditStatus(0);
                purchasesInboundOrderService.save(inboundOrderEntity);

                //3.添加入库明细
                List<PurchaseReceiveOrderDetailEntity> orderItemList = purchaseReceiveOrderDetailService.listByPurchaseReceiverId(id);
                if(CollectionUtils.isNotEmpty(orderItemList)){
                    orderItemList.stream().forEach(item -> {
                        PurchasesInboundOrderDetailEntity inboundOrderDetailEntity = new PurchasesInboundOrderDetailEntity();
                        BeanUtils.copyProperties(item, inboundOrderDetailEntity);
                        inboundOrderDetailEntity.setInboundId(inboundOrderEntity.getInboundId());
                        inboundOrderDetailEntity.setInboundNo(inboundOrderEntity.getInboundNo());
                        inboundOrderDetailEntity.setPurchaseFee(item.getPurchasePrice().multiply(item.getPurchaseCount()));
                        inboundOrderDetailEntity.setPurchaseCount(item.getPurchaseCount());
                        purchasesInboundOrderDetailService.save(inboundOrderDetailEntity);
                    });
                }
            }

            //3、修改审核表状态
            auditParams.setTitle(auditParams.getAuditStatus() == 1 ? "已审核采购收货单" : "审核不通过采购收货单");
            String s = systemFeignService.updateAudit(auditParams);
            log.info("updateAudit result===", s);
        }
    }
}